package org.example.registry;/*
 * Copyright 2016 Google, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.registry.NotifyListener;
import com.alibaba.dubbo.registry.support.FailbackRegistry;
import com.google.gson.reflect.TypeToken;
import io.kubernetes.client.openapi.ApiCallback;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.*;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.KubeConfig;
import io.kubernetes.client.util.Watch;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * kuberntes registry : treat kubernetes as the registry
 * <p>
 * 1） for register, it is done automatically by the processing of orchestration
 * 2)  for service address discovery, watch the resource and update accordingly
 * </p>
 */
public class KubernetesRegistry extends FailbackRegistry {

    private ApiClient client;

    public KubernetesRegistry(URL url) {
        super(url);
        InputStream stream = getClass().getResourceAsStream("/kube.config");
        try {
            client = ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new InputStreamReader(stream))).build();
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
        Configuration.setDefaultApiClient(client);
    }

    @Override
    protected void doRegister(URL url) {

    }

    @Override
    protected void doUnregister(URL url) {

    }

    @Override
    protected void doSubscribe(final URL url, final NotifyListener notifyListener) {
        String target = System.getenv(url.getServiceInterface());
        logger.info("Get target from env:" + target);
        URI targetUri = URI.create(target);
        String[] parts = targetUri.getPath().split("/");

        String namespace = parts[1];
        String name = parts[2];
        int port = Integer.valueOf(parts[3]);

        CoreV1Api api = new CoreV1Api();
        V1EndpointsList endpoints;
        try {
            String fieldSelector = "metadata.name=" + name;
            endpoints = api.listNamespacedEndpoints(namespace, null, null, null, fieldSelector, null, null, null, null, null);
        } catch (ApiException e) {
            throw new IllegalArgumentException(e);
        }

        List<URL> urls = update(endpoints, notifyListener, port);
        notify(url, notifyListener, urls);

        try {
            Watch<V1EndpointsList> watch = Watch.createWatch(client,
                    api.listNamespacedEndpointsCall("default", null, null, null, null, null, null, null, null, Boolean.TRUE, new MyCallback()),
                    new TypeToken<Watch.Response<V1EndpointsList>>() {
                    }.getType());

            for (Watch.Response<V1EndpointsList> response : watch) {
                logger.info(response.object.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private List<URL> update(V1EndpointsList endpoints, final NotifyListener notifyListener, int targetPort) {
        List<URL> servers = new ArrayList<>();
        for (V1Endpoints item : endpoints.getItems()) {
            for (V1EndpointSubset subset : item.getSubsets()) {
                boolean match = false;
                for (V1EndpointPort subsetPort : subset.getPorts()) {
                    if (subsetPort.getPort().equals(targetPort)) {
                        match = true;
                        break;
                    }
                }
                if (match) {
                    for (V1EndpointAddress address : subset.getAddresses()) {
                        servers.add(new URL("dubbo", address.getIp(), targetPort));
                    }
                }
            }
        }
        return servers;
    }

//    private void watch(final NotifyListener notifyListener, String targetNameSpace, String targetName, int targetPort) {
//        kubernetesClient.endpoints().inNamespace(targetNameSpace)
//                .withName(targetName)
//                .watch(new Watcher<Endpoints>() {
//                    @Override
//                    public void eventReceived(Action action, Endpoints endpoints) {
//                        switch (action) {
//                            case MODIFIED:
//                            case ADDED:
//                                update(endpoints, notifyListener, targetPort);
//                                return;
//                            case DELETED:
//                                //TODO
//                                //notifyListener.notify(Collections.emptyList());
//                                return;
//                        }
//                    }
//
//                    @Override
//                    public void onClose(KubernetesClientException e) {
//
//                    }
//                });
//    }

    @Override
    protected void doUnsubscribe(URL url, NotifyListener notifyListener) {
        //TODO
        //Need cancel the watcher
    }

    @Override
    public boolean isAvailable() {
        return true;
    }

    @Override
    public void destroy() {
        super.destroy();
    }


    public static class MyCallback implements ApiCallback<V1EndpointsList> {

        @Override
        public void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders) {
            System.out.println("onFailure");
        }

        @Override
        public void onSuccess(V1EndpointsList result, int statusCode, Map<String, List<String>> responseHeaders) {
            System.out.println("onSuccess");
        }

        @Override
        public void onUploadProgress(long bytesWritten, long contentLength, boolean done) {
            System.out.println("onUploadProgress");
        }

        @Override
        public void onDownloadProgress(long bytesRead, long contentLength, boolean done) {
            System.out.println("onDownloadProgress");
        }
    }
}
